package com.example.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.example.product.dao.CategoryBrandRelationDao;
import com.example.product.entity.CategoryBrandRelationEntity;
import com.example.product.util.CategoryUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.common.utils.PageUtils;
import com.example.common.utils.Query;

import com.example.product.dao.CategoryDao;
import com.example.product.entity.CategoryEntity;
import com.example.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    private CategoryBrandRelationDao categoryBrandRelationDao;
    @Autowired
    private CategoryUtils categoryUtils;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        // 1. 查询所有商品分类
        List<CategoryEntity> entities = baseMapper.selectList(null);
        // 2. 组装成父子树形结构
//        List<CategoryEntity> res = solution1(entities);
        List<CategoryEntity> res = solution2(entities);
        return res;
    }

    @Override
    public void removeItemByIds(List<Long> asList) {
        // TODO 判断要删除的记录是否被其他地方引用，如果已经被引用，则不能删除
        baseMapper.deleteBatchIds(asList);
    }


    private List<CategoryEntity> solution1(List<CategoryEntity> entities) {

        List<CategoryEntity> res = entities.stream()
                // 1. 获取所有一级分类
                .filter(item -> item.getParentCid() == 0)
                // 2. 设置一级分类的子分类
                .map(item -> {item.setChildren(getChildrenCategory(item,entities)); return item;})
                // 3. 排序（从小到大）
                .sorted((item1,item2) -> {return (item1.getSort() == null ? 0 : item1.getSort()) - (item2.getSort() == null ? 0 : item2.getSort());})
                .collect(Collectors.toList());
        return res;
    }

    private List<CategoryEntity> getChildrenCategory(CategoryEntity item,List<CategoryEntity> all) {
        List<CategoryEntity> res = all.stream()
                // 获取子分类
                .filter(entity -> entity.getParentCid() == item.getCatId())
                // 给子分类递归设置子分类
                .map(children -> {
                    children.setChildren(getChildrenCategory(children, all));
                    return children;
                })
                // 排序
                .sorted((item1,item2) -> {return (item1.getSort() == null ? 0 : item1.getSort()) - (item2.getSort() == null ? 0 : item2.getSort());})
                .collect(Collectors.toList());
        return res;
    }

    private List<CategoryEntity> solution2(List<CategoryEntity> entities) {
        // 1. 按parentId分组， key 时parentId value是parentId对应的List<CategoryEntity>
        Map<Long,List<CategoryEntity>> group  = entities.stream().collect(Collectors.groupingBy(CategoryEntity::getParentCid));

        List<CategoryEntity> res = entities.stream()
                // 2. 遍历给entities每个元素设置子分类
                .map(item -> {
                    item.setChildren(group.get(item.getCatId()));
                    return item;
                })
                // 3. 排序
                .sorted((item1, item2) -> {
                    return (item1.getSort() == null ? 0 : item1.getSort()) - (item2.getSort() == null ? 0 : item2.getSort());
                })
                .collect(Collectors.toList());
        return res;
    }


    @Override
    public Long[] getCategoryPathById(Long catelogId) {
        List<Long> list = new ArrayList<>();
        categoryUtils.getCatelogPath(catelogId,list);
        Collections.reverse(list);
        return list.toArray(new Long[list.size()]);
    }

    @Transactional
    @Override
    public void cascaderUpdateById(CategoryEntity category) {
        baseMapper.updateById(category);
        // 在电商项目中，为了避免关联查询，所以在设计表的时候故意设置冗余字段
        // 如果更新了分类名，则需要级联更新其他表引用的分类名
        if (!StringUtils.isEmpty(category.getName())) {
            // 级联更新品牌分类关系表的分类名称
            categoryBrandRelationDao.update(null,new UpdateWrapper<CategoryBrandRelationEntity>()
                    .set("catelog_name",category.getName())
                    .eq("catelog_id",category.getCatId()));
        }

        // TODO 级联更新其他表引用的分类名称
    }
}